<template>
  <div class="person">
    姓:
    <input type="text" v-model="firstName"> <br>
    名：
    <input type="text" v-model="lastName"> <br>
    <button @click="changeFullName">修改全名li-si</button><br>
    全名：<br>
    <!-- 用了4次的值，计算属性只调用一次 -->
    <span>{{ fullName1 }}</span><br>
    <span>{{ fullName1 }}</span><br>
    <span>{{ fullName1 }}</span><br>
    <span>{{ fullName1 }}</span><br>

    <!-- <h3>函数每次都会调用：</h3>
    <hr>
    <span>{{ fullName3() }}</span>
    <hr>
    <span>{{ fullName3() }}</span> -->
  </div>
</template>

<script setup lang="ts" name="Person">
  import { computed, ref } from "vue";
  let firstName = ref('zhang')
  let lastName = ref('san')

  //函数调用每次都会重新执行
  // function fullName3() {
  //   console.log(2);
  //   return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
  // }

  // 计算属性，返回一个ref的值
  // 用到的数据发生变化，才会重新执行。（只读） 无法为“fullName1.value”赋值，因为它是只读属性。
  let fullName1 = computed(() => {
    console.log(1);
    return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
  })

  //这么定义的full是一个（可读写）的ref
  let fullName2 = computed({
    get() {
      return firstName.value.slice(0, 1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
    },
    set(val) {
      let [str1, str2] = val.split('-')
      firstName.value = str1
      lastName.value = str2

      console.log('变化的值：', val);
    }
  })

  function changeFullName() {
    fullName2.value = 'li-si'
  }

</script>

<style scoped>
  .person {
    width: 100%;
    background-color: skyblue;
    box-shadow: 0px 1px 2px #ddd;
    border-radius: 10px;
    padding: 20px;
  }

  button {
    margin: 0 5px;
  }

  li {
    font-size: 20px;
  }
</style>
